/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-11-03 10:15:52
 * @LastEditTime: 2023-02-15 18:52:09
 */
import { createContext, useReducer, useEffect, useContext } from 'react';
import {
  SET_SELECT_FOND,
  SET_SELECT_AT,
  SET_FIRST_AT,
  SET_TARGET_AT,
  SET_SOURCE_AT,
  SET_SELECT_KEY,
  GET_CURRENT,
  GET_TATLIST,
  ADD_TATLIST,
  EDIT_TATLIST,
  DEL_TATLIST
} from '../constants';
import { MappingRelationReducer } from '../reducers/MappingRelationReducer';
import { fetchATListByFondId } from '@/api/archivesType';
import { fetchMetadata } from '@/api/metadata';
import { message, Modal } from 'antd';
import { fetchMappingByPage, addMapping, editMapping, deleteMappingList } from '@/api/mapping';
import { useMappingRouterTypeContext } from '../contexts/MappingRouterTypeContext';

const initialState = {
  baseParam: [
    { label: '资料库', type: 1 },
    { label: '档案征集', type: 2 },
    { label: '收发文登记', type: 3 }
  ],
  // 当前选中的项目
  selectFond: {},
  selectAT: {},
  current: null,
  FATList: [],
  TATList: [],
  selectItems: [],
  /* 下面俩忘了有没有用了 */
  hierachy: [],
  base: {},
  /* 映射表下拉选项 */
  targetItems: [],
  fileList: []
};
const MappingRelationContext = createContext();
const MappingRelationContextProvider = (props) => {
  const [state, dispatch] = useReducer(MappingRelationReducer, initialState);
  const { routerType } = useMappingRouterTypeContext();

  const actions = {
    /**
     * @description: 设置选中全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },
    getArchiveTypeList(id) {
      fetchATListByFondId(id, routerType).then((res) => {
        const data = res.data;
        dispatch({ type: SET_FIRST_AT, data });
      });
    },
    /* 设置源列表数据 */
    setFileList(data) {
      fetchMetadata(data).then((res) => {
        const { data } = res;
        console.log('data?', data);
        dispatch({ type: SET_SOURCE_AT, data });
      });
    },
    /* 设置目标列表数据 */
    setTargetItems(data) {
      fetchMetadata(data).then((res) => {
        const { data } = res;
        dispatch({ type: SET_TARGET_AT, data });
      });
    },
    setSelectKey(data) {
      dispatch({ type: SET_SELECT_KEY, data });
    },
    /* 获取选择类型 */
    getCurrent(data) {
      dispatch({ type: GET_CURRENT, data });
    },

    getTATList(prams) {
      return new Promise((resolve, reject) => {
        fetchMappingByPage(prams)
          .then((res) => {
            const { data } = res;
            dispatch({ type: GET_TATLIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            dispatch({ type: GET_TATLIST, data: [] });
            reject(err);
          });
      });
    },
    addTAT(params) {
      return new Promise((resolve, reject) => {
        addMapping({ ...params })
          .then((res) => {
            const { data } = res;
            dispatch({ type: ADD_TATLIST, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },
    editTAT(params) {
      return new Promise((resolve, reject) => {
        editMapping({ ...params })
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_TATLIST, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },
    delTAT(id, title = '确认删除该映射？') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteMappingList(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((item) => parseInt(item, 10));
            dispatch({ type: DEL_TATLIST, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
      // dispatch({ type: DEL_TATLIST, id });
    }
  };
  useEffect(() => {
    // if (state.selectFond?.id) {
    // TODO 暂时还没有接口
    actions.getArchiveTypeList(5);
    // actions.getArchiveTypeList({ id: 107 });
    // }
  }, [state.selectFond]);

  const filters = {
    calssFilter(id) {
      return state.baseParam.find((item) => item.type === id)?.label || '-';
    }
  };
  return (
    <MappingRelationContext.Provider value={{ ...state, ...actions, ...filters }}>
      {props.children}
    </MappingRelationContext.Provider>
  );
};
export const useMappingRelationContext = () => {
  return useContext(MappingRelationContext);
};
export { MappingRelationContext, MappingRelationContextProvider };
